require 'app/models/political_group_vote'
require 'app/models/political_group'
require 'app/models/vote'

class Statistician
  def political_group_votes(sitting)
    sitting.questions.each do |question|
      sql_time = "select distinct time from votes where question_id = #{question.id}"
      r = ActiveRecord::Base.connection.execute(sql_time)
      while row = r.fetch_row do
        time = row[0]
        PoliticalGroup.find(:all).each do |pg|
          pgv = PoliticalGroupVote.new(:question_id => question.id, :political_group_id => pg.id)
          pgv.time = time
          pgv.action_absent = Vote.count(:all, :conditions => {:question_id => question.id, :political_group_id => pg.id, :time => time, :action => Vote::ABSTAIN})
          pgv.action_novote = Vote.count(:all, :conditions => {:question_id => question.id, :political_group_id => pg.id, :time => time, :action => Vote::NOVOTE})
          pgv.action_abstain = Vote.count(:all, :conditions => {:question_id => question.id, :political_group_id => pg.id, :time => time, :action => Vote::ABSTAIN})
          pgv.action_no = Vote.count(:all, :conditions => {:question_id => question.id, :political_group_id => pg.id, :time => time, :action => Vote::NO})
          pgv.action_yes = Vote.count(:all, :conditions => {:question_id => question.id, :political_group_id => pg.id, :time => time, :action => Vote::YES})
          pgv.save
        end
      end
    end

    #dabar paskaiciuojam maistus
    sitting.questions.each do |question|
      question.votes.find(:all, :conditions=>"(action = 4 OR action = 5)").each do |vote|
        pgv = PoliticalGroupVote.find(
          :first,
          :conditions => {:question_id => vote.question.id, :political_group_id => vote.political_group.id, :time => vote.time}
        )
        abstain = pgv.action_abstain
        yes = pgv.action_yes
        no = pgv.action_no
        if abstain < yes or abstain < no then
          vote.group_rebellion = vote.action == Vote::YES ? yes < no : yes > no
        else
          vote.group_rebellion = false
        end

        p_abstain = Vote.count(:all, :conditions => {:question_id => vote.question.id, :time => vote.time, :action => Vote::ABSTAIN})
        p_yes = Vote.count(:all, :conditions => {:question_id => vote.question.id, :time => vote.time, :action => Vote::YES})
        p_no = Vote.count(:all, :conditions => {:question_id => vote.question.id, :time => vote.time, :action => Vote::NO})
        if p_abstain < p_yes or p_abstain < p_no then
          vote.parliament_rebellion = vote.action == Vote::YES ? p_yes < p_no : p_yes > p_no
        else
          vote.parliament_rebellion = false
        end
        vote.save
      end
    end
  end
end
